#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : fengge-python_advance
@File : util.py
@Author : Royce
@Time : 2025/7/7 11:35
@脚本说明 :
封装一些常用的工具类
"""
import threading
import time
from functools import wraps


def timer(unit='s', need_func_param=False):
    """仅为主线程计时的装饰器"""

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                # 确定时间单位
                suffix = 'ms' if unit == 'ms' else 's'

                start = time.perf_counter()
                result = func(*args, **kwargs)
                elapsed = time.perf_counter() - start

                # 单位转换
                if unit == 'ms': elapsed *= 1000

                # 将函数的参数收集起来, 最后将参数输出
                params = []
                if args:
                    params.append('\n'.join(map(str, args)))
                if kwargs:
                    params.append('\n'.join(map(str, kwargs.items())))
                param_str = '\n'.join(map(str, params))

                output = f"线 程: {threading.current_thread().name} | 函数: {func.__name__} 执行完成 " \
                         f"| 耗时: {elapsed:.4f}{suffix} \n"

                if need_func_param:
                    output += f"函数参数: \n{param_str}\n\n"

                print(output, end='')
                return result
            except Exception as e:
                print(f"装饰器错误: {e}")  # 捕获具体异常
                return func(*args, **kwargs)

        return wrapper

    return decorator
